package com.guosen.zebra.framework.starter.s3.autoconfigure;


import com.amazonaws.ClientConfiguration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.guosen.zebra.framework.starter.s3.properties.S3Properties;
import com.guosen.zebra.framework.starter.s3.service.ZebraS3Service;
import com.guosen.zebra.framework.starter.s3.service.impl.ZebraS3ServiceImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * S3 自动配置类
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(S3Properties.class)
public class S3AutoConfiguration {

    /**
     * AWS S3 原生客户端
     * @param s3Properties S3 配置
     * @return S3 bean
     */
    @Bean
    public AmazonS3 amazonS3(S3Properties s3Properties) {
        AWSCredentials credentials = new BasicAWSCredentials(s3Properties.getAk(), s3Properties.getSk());
        // 使用默认的配置，以后用户有需要再开放
        ClientConfiguration clientConfig = new ClientConfiguration();

        AwsClientBuilder.EndpointConfiguration endpointConfiguration =
                new AwsClientBuilder.EndpointConfiguration(s3Properties.getEndpoint(), Regions.DEFAULT_REGION.getName());

        return AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withClientConfiguration(clientConfig)
                .withEndpointConfiguration(endpointConfiguration)
                .build();
    }

    /**
     * Zebra 提供的S3服务，封装常见S3操作
     * @param s3Properties  S3 配置
     * @param amazonS3  S3 客户端
     * @return Zebra S3 服务
     */
    @Bean
    public ZebraS3Service zebraS3Service(S3Properties s3Properties, AmazonS3 amazonS3) {
        return new ZebraS3ServiceImpl(s3Properties, amazonS3);
    }
}
